/*
 * Copyright (c) 2020. Bailiang All rights reserved. 广州百量科技有限公司 版权所有
 * 请勿修改或删除版权声明及文件头部.
 */

package top.hundreds.oasys.config.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import top.hundreds.oasys.bean.constant.SystemConst;
import top.hundreds.common.utils.JJwtUtil;
import top.hundreds.common.web.api.ApiResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(SystemConst.USER_TOKEN_HEADER);
        if (StrUtil.isBlank(token)) {
            response.setContentType("application/json; charset=utf-8");
            response.getWriter().write(JSONUtil.toJsonStr(ApiResult.expire()));
            response.getWriter().flush();
            return false;
        } else {
            try {
                Claims claims = JJwtUtil.parseJWT(token, SystemConst.USER_JWT_KEY);
                request.setAttribute("id", claims.getId());
                request.setAttribute("name", claims.get("name"));
            } catch (Exception e) {
                response.setContentType("application/json; charset=utf-8");
                response.getWriter().write(JSONUtil.toJsonStr(ApiResult.expire()));
                response.getWriter().flush();
                return false;
            }
        }
        return true;
    }
}
